/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.mvc.condition;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.cors.CorsUtils;

/**
 * A logical disjunction (' || ') request condition that matches a request
 * against a set of {@link RequestMethod}s.
 *
 * @author Arjen Poutsma
 * @author Rossen Stoyanchev
 * @since 3.1
 */
public final class RequestMethodsRequestCondition extends AbstractRequestCondition<RequestMethodsRequestCondition> {

	private static final RequestMethodsRequestCondition GET_CONDITION = new RequestMethodsRequestCondition(RequestMethod.GET);

	/**保存请求方法集合
	 */
	private final Set<RequestMethod> methods;


	/**构造函数，传入参数为RequestMethod集合
	 * <br/>Create a new instance with the given request methods.
	 * @param requestMethods 0 or more HTTP request methods; if, 0 the condition will match to every request
	 */
	public RequestMethodsRequestCondition(RequestMethod... requestMethods) {
		// 数组转换为list
		this(asList(requestMethods));
	}

	/**通过list构造对象，主要目的是为了把传入的数组转换为Set存储
	 * @param requestMethods
	 */
	private RequestMethodsRequestCondition(Collection<RequestMethod> requestMethods) {
		// 指定method集合为不可修改的集合，内容为传入的请求方法数组内容
		this.methods = Collections.unmodifiableSet(new LinkedHashSet<RequestMethod>(requestMethods));
	}


	private static List<RequestMethod> asList(RequestMethod... requestMethods) {
		return (requestMethods != null ? Arrays.asList(requestMethods) : Collections.<RequestMethod>emptyList());
	}


	/**
	 * Returns all {@link RequestMethod}s contained in this condition.
	 */
	public Set<RequestMethod> getMethods() {
		return this.methods;
	}

	// 重写父类getContent方法，返回条件的请求方法集合
	@Override
	protected Collection<RequestMethod> getContent() {
		return this.methods;
	}

	@Override
	protected String getToStringInfix() {
		return " || ";
	}

	/**当类型上标记了@RequestMapping，方法上也标记了@RequestMapping时，需要合并两个请求方法条件
	 * <br/>Returns a new instance with a union of the HTTP request methods from "this" and the "other" instance.
	 */
	@Override
	public RequestMethodsRequestCondition combine(RequestMethodsRequestCondition other) {
		Set<RequestMethod> set = new LinkedHashSet<RequestMethod>(this.methods);
		set.addAll(other.methods);
		// 把两个条件的请求方法集合合并后，返回一个新的请求方法条件
		return new RequestMethodsRequestCondition(set);
	}

	/**当methods属性为空或者包含当前请求方法时，视为当前请求与该条件匹配
	 * <br/>Check if any of the HTTP request methods match the given request and
	 * return an instance that contains the matching HTTP request method only.
	 * @param request the current request
	 * @return the same instance if the condition is empty (unless the request
	 * method is HTTP OPTIONS), a new condition with the matched request method,
	 * or {@code null} if there is no match or the condition is empty and the request method is OPTIONS.
	 */
	@Override
	public RequestMethodsRequestCondition getMatchingCondition(HttpServletRequest request) {
		// 如果是跨域请求中的预检请求
		if (CorsUtils.isPreFlightRequest(request)) {
			// 则执行特殊匹配逻辑，内部从请求头Access-Control-Request-Method获取请求方法，再执行matchRequestMethod
			return matchPreFlight(request);
		}

		// 如果当前条件中的请求方法集合为空
		if (getMethods().isEmpty()) {
			// 对于请求方法为OPTIONS的请求，无须返回匹配结果，有统一的处理逻辑
			if (RequestMethod.OPTIONS.name().equals(request.getMethod()) &&
					!DispatcherType.ERROR.equals(request.getDispatcherType())) {
				// 固定返回null，表示不匹配
				return null; // No implicit match for OPTIONS (we handle it)
			}
			// 不是OPTIONS，且当前条件请求方法合集为空，返回匹配结果不为空，结果是当前实例。用于表示有匹配结果，以实现未提供该属性时视为匹配的目的，此时匹配结果中的methods元素数为0
			return this;
		}

		// 其他情况，使用匹配请求方法逻辑判断
		return matchRequestMethod(request.getMethod());
	}

	/**
	 * On a pre-flight request match to the would-be, actual request.
	 * Hence empty conditions is a match, otherwise try to match to the HTTP
	 * method in the "Access-Control-Request-Method" header.
	 */
	private RequestMethodsRequestCondition matchPreFlight(HttpServletRequest request) {
		if (getMethods().isEmpty()) {
			return this;
		}
		String expectedMethod = request.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD);
		return matchRequestMethod(expectedMethod);
	}

	private RequestMethodsRequestCondition matchRequestMethod(String httpMethodValue) {
		// 把请求方法解析为HttpMethod枚举
		HttpMethod httpMethod = HttpMethod.resolve(httpMethodValue);
		// 请求条件不为空，进入判断逻辑
		if (httpMethod != null) {
			// 遍历当前条件中请求方法集合，如果与当前请求匹配，则返回请求方法条件实例作为匹配结果，实例内部保存了匹配的方法
			for (RequestMethod method : getMethods()) {
				if (httpMethod.matches(method.name())) {
					// 使用新的请求条件实例作为匹配结果返回，实例内包含了匹配的请求方法，用于表示匹配结果，此时匹配结果中methods集合元素数为1
					return new RequestMethodsRequestCondition(method);
				}
			}
			// 请求方法是HEAD时，且条件集合包括了GET请求，则返回GET请求的条件结果，为了支持HEAD请求提供的特殊处理
			if (httpMethod == HttpMethod.HEAD && getMethods().contains(RequestMethod.GET)) {
				return GET_CONDITION;
			}
		}
		// 无匹配结果时返回null
		return null;
	}

	/**当一个请求有多个匹配结果时，需要对匹配结果进行排序。排序对象是方法getMatchingCondition返回的匹配结果，由匹配逻辑可知，返回结果中methods集合大小为1或0。
	 * <br/>为1表示匹配@RequestMapping注解中声明的请求方法条件，为0表示@RequestMapping中方法属性为空，视为全匹配。
	 * <br/>在对这两个匹配结果进行排序时，基于匹配条件越明确，则匹配结果越好的规则，必然是提供方法属性条件时的匹配结果要优于全匹配结果。那么其实现逻辑就应该有判断结果集合大小的操作
	 * <br/>判断两个匹配结果的大小，返回负数表示当前结果排序在参数other之前，在对匹配结果排序时也越靠前，正数反之，0则相等
	 * <br/>Returns:
	 * <ul>
	 * <li>0 if the two conditions contain the same number of HTTP request methods
	 * <li>Less than 0 if "this" instance has an HTTP request method but "other" doesn't
	 * <li>Greater than 0 "other" has an HTTP request method but "this" doesn't
	 * </ul>
	 * <p>It is assumed that both instances have been obtained via
	 * {@link #getMatchingCondition(HttpServletRequest)} and therefore each instance
	 * contains the matching HTTP request method only or is otherwise empty.
	 */
	@Override
	public int compareTo(RequestMethodsRequestCondition other, HttpServletRequest request) {
		// 当条件中请求方法集合大小不同时，返回差值。size越大，条件越明确
		if (other.methods.size() != this.methods.size()) {
			return other.methods.size() - this.methods.size();
		}
		else if (this.methods.size() == 1) {
			// HEAD请求优先于GET请求
			if (this.methods.contains(RequestMethod.HEAD) && other.methods.contains(RequestMethod.GET)) {
				return -1;
			}
			else if (this.methods.contains(RequestMethod.GET) && other.methods.contains(RequestMethod.HEAD)) {
				return 1;
			}
		}
		return 0;
	}

}
